package org.xurui.bsj.protocol.command.impl;

import lombok.extern.slf4j.Slf4j;
import org.jetlinks.core.message.CommonDeviceMessage;
import org.jetlinks.core.message.DeviceMessage;
import org.jetlinks.core.message.codec.EncodedMessage;
import org.jetlinks.core.message.codec.FromDeviceMessageContext;
import org.jetlinks.core.message.function.FunctionInvokeMessage;
import org.jetlinks.core.message.function.FunctionInvokeMessageReply;
import org.jetlinks.core.message.function.FunctionParameter;
import org.springframework.util.StringUtils;
import org.xurui.bsj.protocol.cache.ConcurrentMapCache;
import org.xurui.bsj.protocol.command.CmdCodec;
import org.xurui.bsj.protocol.enums.CommandEnum;
import org.xurui.bsj.protocol.msg.BsjMessage;
import org.xurui.bsj.protocol.msg.BsjMessageBuilder;
import org.xurui.bsj.protocol.utils.ArrayUtils;
import org.xurui.bsj.protocol.utils.BinaryUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 4.2.1.设置呼入号码
 */
@Slf4j
public class CmdCodec_SET_INCOMING_CALL implements CmdCodec {
    @Override
    public boolean supportsCmd(String cmd) {
        return CommandEnum.SET_INCOMING_CALL.name().equals(cmd);
    }

    @Override
    public List<DeviceMessage> parsePayload(BsjMessage payload, FromDeviceMessageContext context) {
        //例子：[35380100360174,898600MFSSYYGXXXXXXP,201805082000001000,SET_INCOMING_CALL,2,1,0]
        FunctionInvokeMessageReply report = FunctionInvokeMessageReply.create();
        report.setDeviceId(payload.getHeader().getDeviceNo());
        report.setFunctionId(payload.getHeader().getCmd());
        Object messageIdObj = ConcurrentMapCache.getInstance().getAndRemove(payload.getHeader().getOrderNo());
        String messageId = messageIdObj==null?null:messageIdObj.toString();
        if(messageId==null){
            messageId = payload.getHeader().getOrderNo();
        }
        report.setMessageId(messageId);
        report.setTimestamp(System.currentTimeMillis());
        Map<String, Object> properties = new HashMap<>();
        String tempBody = payload.getTempBody();
        String[] tempBodyArr = tempBody.split("@");
        //properties.put("header", FastBeanCopier.copy(payload.getHeader(), HashMap::new));
        properties.put("header", payload.getHeader().toMap());
        //应答状态(0=设置成功;1=设置异常;)
        properties.put("responseStatus", ArrayUtils.getStrByIndex(tempBodyArr,0));
        report.setOutput(properties);
        return genDeviceMessage(report);
    }

    @Override
    public EncodedMessage encodeMessage(CommonDeviceMessage message,String zzs) {
        //平台下发消息
        //例子：[35380100360174,898600MFSSYYGXXXXXXP,201805082000001000,SET_INCOMING_CALL,1,20180528111820,112,13900000000!13900000001!13900000002!13900000003!@13900000004=0600-2230+!13900000005=0300-0600+0900-1130+!@2@0+1+2+3+4+5+6]
        /**
         * 报文体格式： 删除号码
         *            @添加号码和时段
         *            @呼入限制
         *            @周期
         * 字段说明：   1.无删除号码或者无添加号码可用0代替 例如0@13900000004=0600-2230+!@呼入限制@周期 13900000004@0@呼入限制@周期 最多允许20个白名单用户;
         *            2.每个白名单号码允许设 置两个呼入时段 删除号码和时段(呼入号码) 删除的时候，会将2个时段内的数据全部删除
         *             添加号码和时段(呼入号码=开始时间-结束时间+开 始时间-结束时间+) 13900000000!13900000001!13900000002!13900000003!@13900000004=0600-2230+!13900000005=0900-1130+!
         *            3.呼入限制：1、无限制 2、限制白名单以外的号码呼 入 3、限制所有号码呼入
         *            4.周期：周一至周六用1-6表示，周日用0表示，如 1+2+3+4+表示周一至周四
         */
        if(message instanceof FunctionInvokeMessage) {
            FunctionInvokeMessage m = (FunctionInvokeMessage) message;
            List<FunctionParameter> params = m.getInputs();
            Map<String, Object> paramsMap = params.stream()
                .collect(Collectors.toMap(FunctionParameter::getName, FunctionParameter::getValue));
            String  delAddPhoneTimes="";
            if(paramsMap.get("delAddPhoneTimes")!=null && !paramsMap.get("delAddPhoneTimes").equals("")) {
                delAddPhoneTimes=paramsMap.get("delAddPhoneTimes").toString();
            }

            String incomeCall="";
            if(paramsMap.get("incomeCall")!=null && !paramsMap.get("incomeCall").equals("")) {
                incomeCall=paramsMap.get("incomeCall").toString();
            }

            String cycle="";
            if(paramsMap.get("cycle")!=null && !paramsMap.get("cycle").equals("")) {
                cycle=paramsMap.get("cycle").toString();
            }


            if(StringUtils.isEmpty(delAddPhoneTimes)){
                log.error("删除和添加号码为空请重新填写");
                return null;
            }
            StringBuffer sb = new StringBuffer();
            sb.append(delAddPhoneTimes);
            sb.append(BinaryUtils.CMD_AT);
            sb.append(incomeCall);
            sb.append(BinaryUtils.CMD_AT);
            sb.append(cycle);

            return BsjMessageBuilder.create().buildBsjFunctionInvoickMessage(m,sb.toString());
        }else{
            if (log.isDebugEnabled()) {
                log.debug("非FunctionInvokeMessage指令{}消息{}",CommandEnum.SET_INCOMING_CALL.name(),message);
            }
            return null;
        }

    }
}
